﻿using System;
using System.Collections.Generic;
using Microsoft.SharePoint;
using SpWiki.Lib.Repository;
using WikiPlex.Formatting.Renderers;
using System.Web.Mvc;

namespace SpWiki.Lib.Wiki
{
    public class TitleLinkRenderer : Renderer
    {
        private const string LinkFormatExisting = "<a href=\"{0}\">{1}</a>";
        private const string LinkFormatNew = "<a href=\"{0}\" class=\"new\">{1}</a>";
        private readonly UrlHelper _urlHelper;
        private readonly SpWikiLibrary _spWikiLibrary;

        /// <summary>
        /// Prevents a default instance of the <see cref="TitleLinkRenderer"/> class from being created.
        /// </summary>
        private TitleLinkRenderer() : this(null, null) { }

        /// <summary>
        /// Initializes a new instance of the <see cref="TitleLinkRenderer"/> class.
        /// </summary>
        /// <param name="spWikiLibrary">The sp wiki library.</param>
        public TitleLinkRenderer(SpWikiLibrary spWikiLibrary) : this(null, spWikiLibrary) { }

        /// <summary>
        /// Prevents a default instance of the <see cref="TitleLinkRenderer"/> class from being created.
        /// </summary>
        /// <param name="urlHelper">The URL helper.</param>
        /// <param name="spWikiLibrary">The sp wiki library.</param>
        private TitleLinkRenderer(UrlHelper urlHelper, SpWikiLibrary spWikiLibrary)
        {
            _urlHelper = urlHelper;
            _spWikiLibrary = spWikiLibrary;
        }

        /// <summary>
        /// Gets the collection of scope names for this <see cref="IRenderer"/>.
        /// </summary>
        protected override ICollection<string> ScopeNames
        {
            get { return new[] {WikiScopeName.WikiLink}; }
        }

        /// <summary>
        /// Will expand the input into the appropriate content based on scope for the derived types.
        /// </summary>
        /// <param name="scopeName">The scope name.</param>
        /// <param name="input">The input to be expanded.</param>
        /// <param name="htmlEncode">Function that will html encode the output.</param>
        /// <param name="attributeEncode">Function that will html attribute encode the output.</param>
        /// <returns>
        /// The expanded content.
        /// </returns>
        protected override string PerformExpand(string scopeName, string input, Func<string, string> htmlEncode, Func<string, string> attributeEncode)
        {
            var file = SpWikiLibrary.GetSpWikiFileByName(input);
            var url = file != null ? file.ViewUrl : _spWikiLibrary.GetEditNewFileUrl(input);
            var linkFormat = file != null ? LinkFormatExisting : LinkFormatNew;
            return string.Format(linkFormat, attributeEncode(url), htmlEncode(input));
        }

        //private string c
    }
}